package cn.signalpha.modules.auth.granter;

import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.social.props.SocialProperties;
import cn.signalpha.core.social.utils.SocialUtil;
import cn.signalpha.core.tool.utils.BeanUtil;
import cn.signalpha.core.tool.utils.WebUtil;
import cn.signalpha.modules.auth.dto.UserInfo;
import cn.signalpha.modules.auth.provider.ITokenGranter;
import cn.signalpha.modules.auth.provider.TokenParameter;
import cn.signalpha.modules.com.entity.UserOauth;
import cn.signalpha.modules.com.entity.enums.UserSourceEnum;
import cn.signalpha.modules.com.service.UserService;
import lombok.AllArgsConstructor;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * SocialTokenGranter
 */
@Component
@AllArgsConstructor
public class SocialTokenGranter implements ITokenGranter {

	public static final String GRANT_TYPE = "social";

	private static final Integer AUTH_SUCCESS_CODE = 2000;

	private final UserService userService;
	private final SocialProperties socialProperties;

	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		HttpServletRequest request = WebUtil.getRequest();

		// 开放平台来源
		String sourceParameter = request.getParameter("source");
		// 匹配是否有别名定义
		String source = socialProperties.getAlias().getOrDefault(sourceParameter, sourceParameter);
		// 开放平台授权码
		String code = request.getParameter("code");
		// 开放平台状态吗
		String state = request.getParameter("state");

		// 获取开放平台授权数据
		AuthRequest authRequest = SocialUtil.getAuthRequest(source, socialProperties);
		AuthCallback authCallback = new AuthCallback();
		authCallback.setCode(code);
		authCallback.setState(state);
		AuthResponse authResponse = authRequest.login(authCallback);
		AuthUser authUser;
		if (authResponse.getCode() == AUTH_SUCCESS_CODE) {
			authUser = (AuthUser) authResponse.getData();
		} else {
			throw new ServiceException("授权登陆失败");
		}

		// 组装数据
		UserOauth userOauth = Objects.requireNonNull(BeanUtil.copy(authUser, UserOauth.class));
		userOauth.setOpenId(authUser.getUuid());
		userOauth.setSource(authUser.getSource());
		userOauth.setNickName(authUser.getNickname());
		if(UserSourceEnum.WECHAT_OPEN.getValue().equals(userOauth.getSource())){
			userOauth.setUnionId(authUser.getRawUserInfo().getString("unionid"));
		}
		return userService.userInfo(userOauth);
	}

}
